package org.dromara.todolist.controller;



import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.ServletUtils;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.log.event.LogininforEvent;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISysClientService;
import org.dromara.system.service.ISysUserService;
import org.dromara.todolist.domain.vo.TodoLoginVo;
import org.dromara.todolist.domain.vo.TodoRegisterBody;
import org.dromara.todolist.service.TodoIAuthStrategy;
import org.dromara.todolist.service.TodoLoginService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证
 *
 * @author Lion Li
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@SaIgnore
@RequestMapping("/td/auth")
public class TodoAuthController {

    private final SysUserMapper userMapper;
    private final ISysUserService userService;
    private final ISysClientService clientService;
    private final TodoLoginService todoLoginService;


    @PostMapping("/login")
    public R<TodoLoginVo> login (@RequestBody TodoRegisterBody loginBody){

        System.out.println(loginBody);
        String grantType = loginBody.getGrantType();

        // 认证客户端id
        String clientId = loginBody.getClientId();

        SysClientVo client = clientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!UserConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        todoLoginService.checkTenant(loginBody.getTenantId());

        String body = JSONUtil.toJsonStr(loginBody);
        // 登录
        TodoLoginVo loginVo = TodoIAuthStrategy.login(body, client, grantType);


//        Long userId = LoginHelper.getUserId();

        return R.ok(loginVo);
    }

    @PostMapping("/register")
    public R<Void> register ( @RequestBody TodoRegisterBody registerBody) {

        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        String email = registerBody.getEmail();
        String phoneNumber = registerBody.getPhonenumber();
        String tenantId = registerBody.getTenantId();

        // 认证客户端id
        String clientId = registerBody.getClientId();

        SysClientVo client = clientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || StringUtils.isBlank(client.getGrantType())) {
            return R.fail(MessageUtils.message("auth.clientid.not.blank"));
        }

        String deviceType = client.getDeviceType();
        // 校验用户类型是否存在
        String userType = UserType.getUserTypeByDevice(deviceType);


        SysUserBo sysUser = new SysUserBo();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setEmail(email);
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setUserType(userType);

        boolean exist = TenantHelper.dynamic(tenantId, () -> {
            return userMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, sysUser.getUserName()));
        });

        if (exist) {
            throw new UserException("user.register.save.error", username);
        }
        boolean regFlag = userService.registerUser(sysUser, tenantId);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }
        // 清空短信缓存
//        RedisUtils.deleteObject(key);

        recordLogininfor(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
        return R.ok("user.register.success");


    }



    /**
     * 记录登录信息
     *
     * @param tenantId 租户ID
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    private void recordLogininfor(String tenantId, String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setTenantId(tenantId);
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

}


